package com.ctrip.corp.obt.shard.handler;


import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.shard.context.DataShardContext;
import com.ctrip.corp.obt.shard.handler.strategy.ITableRouteStrategy;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/02/09
 * @desc 默认 IShardingHandler
 * @see
 * @since 1.0
 */
public class DefaultShardingHandler implements IShardingHandler {

    private final Map<String, ITableRouteStrategy> tableRouteStrategyMap;

    public DefaultShardingHandler(List<ITableRouteStrategy> tableRouteStrategyList) {
        this.tableRouteStrategyMap = tableRouteStrategyList.stream().collect(Collectors.toMap(ITableRouteStrategy::strategyName, Function.identity()));
    }

    @Override
    public void preShard(String tableShardStrategy) {
        // 选择tableShard策略，并进行table route
        Optional.ofNullable(tableRouteStrategyMap.get(tableShardStrategy))
                .ifPresent(strategy -> DataShardContext.setTableShardSource(strategy.routeTable(TenantContext.getTenantId())));
        // targetDataSource由ShardInfo中的信息根据租户信息来控制
//        DataShardContext.setDBShardSource(Optional.ofNullable(targetDataSource).orElse(DEFAULT));
    }

    @Override
    public Set<String> getStrategies() {
        return tableRouteStrategyMap.keySet();
    }

}
